package com.jiuyuan.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiuyuan.entity.Menu;
import com.jiuyuan.entity.Role;
import com.jiuyuan.entity.RoleMenu;
import com.jiuyuan.entity.vo.RespBean;
import com.jiuyuan.service.IMenuService;
import com.jiuyuan.service.IRoleMenuService;
import com.jiuyuan.service.IRoleService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: hrms
 * @description:
 * @author: Feng
 * @create: 2023-02-16 17:09
 **/

@RestController
@RequestMapping("/system/basic/permission")
public class PermissionController {
    @Autowired
    IRoleService roleService;
    @Autowired
    IMenuService MenuService;
    @Autowired
    IRoleMenuService roleMenuService;

    @ApiOperation("查询所有菜单")
    @GetMapping("/allMenus")
    public RespBean listAllMenus(){
        //三级菜单，第一级是空的
        return RespBean.success(MenuService.listAll());
    }

    @ApiOperation("通过角色id查询菜单id")
    @GetMapping("/{id}")
    public RespBean getMidsbyRid(Integer id){
        List<Integer> mids = roleMenuService.list(new QueryWrapper<RoleMenu>()
                .eq("roleId", id)
        ).stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
        return RespBean.success(mids);
    }

    @ApiOperation("更新角色的菜单")
    @PutMapping("/{id}")
    public RespBean updateMenusId(@PathVariable int id,Integer[] ids){
        roleMenuService.remove(new QueryWrapper<RoleMenu>().eq("roleId",id));
        if(ids==null || ids.length==0) return RespBean.success("更新成功");
        int result = roleMenuService.saveRoleMenu(id,ids);
        if(result==ids.length) return RespBean.success("更新成功");
        return RespBean.error("更新失败");

    }

    @GetMapping("/allRoles")
    @ApiOperation("查询所有角色")
    public RespBean listAllRoles(){
        return RespBean.success(roleService.list());
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除")
    public RespBean delete(@PathVariable Integer id){
        boolean byId = roleService.removeById(id);
        if(byId) return RespBean.success("删除成功");
        return RespBean.error("删除失败");
    }

    @PostMapping("/")
    @ApiOperation("增加")
    public RespBean add(Role role){
        if(!role.getName().startsWith("ROLE_")) role.setName("ROLE_"+role.getName());
        boolean byId = roleService.save(role);
        if(byId) return RespBean.success("添加成功");
        return RespBean.error("添加失败");
    }
}
